package com.dfrz.problem.service.impl;

import java.util.Iterator;
import java.util.List;

import com.dfrz.problem.dao.ProblemDao;
import com.dfrz.problem.model.Employee;
import com.dfrz.problem.model.ProblemInfo;
import com.dfrz.problem.model.ProjectInfo;
import com.dfrz.problem.service.ProblemService;
import com.dfrz.problem.utils.IConstant;
import com.dfrz.problem.utils.Result;

public class ProblemServiceImpl implements ProblemService {
	private ProblemDao problemDao;
	
	@Override
	public void addProblem(Integer employeeId,ProblemInfo problem,ProjectInfo project) {
		problem.setProject(project);
		problemDao.addProblem(employeeId,problem);
	}

	@Override
	public Result<List<ProblemInfo>> getListProblem(Employee employee) {
		Result<List<ProblemInfo>> result = new Result<List<ProblemInfo>>();
		// 根据员工类型进行问题查询
		
		if(employee.getRole().getRoleId() == 2){
			// 项目经理可查看项目所有问题信息
			result.setResult(problemDao.getListOnPM(employee.getProject().getProjectId()));
		}else if(employee.getRole().getRoleId() == 3){
			// 测试员可查看自己所提出和待测试的问题信息
			List<ProblemInfo> list = problemDao.getListProblem(employee.getEmployeeId(),2);
			
			result.setResult(list);
		}else if(employee.getRole().getRoleId() == 4){
			// 开发员可查看自己所解决和待解决的问题
			List<ProblemInfo> list = problemDao.getListProblem(employee.getEmployeeId(),3);
			Iterator<ProblemInfo> it = problemDao.getListProblem(employee.getEmployeeId(),2).iterator();
			while(it.hasNext()){
				ProblemInfo p = it.next();
				int i;
				for(i=0; i<list.size(); i++){
					if(list.get(i).getProblemId() == p.getProblemId()){
						break;
					}
				}
				if(i >= list.size() && employee.getProject().getProjectId() == p.getProject().getProjectId()){
					list.add(p);
				}
			}
			result.setResult(list);
		}else{
			result.setCode(IConstant.NOT_LOGIN);
		}
		
		return result;
	}
	
	public void setProblemDao(ProblemDao problemDao) {
		this.problemDao = problemDao;
	}

	@Override
	public Result<ProblemInfo> getProblemOnId(int problemId) {
		Result<ProblemInfo> result = new Result<ProblemInfo>();
		if(problemId <= 0){
			result.setCode(IConstant.PROBLEM_NOT_EXIST);
			return result;
		}
		ProblemInfo problem = problemDao.getProblem(problemId);
		if(problem != null){
			result.setResult(problem);
		}else{
			result.setCode(IConstant.PROBLEM_NOT_EXIST);
		}
		
		return result;
	}

	@Override
	public void payoutProblem(ProblemInfo problem, Integer selectWork) {
		problemDao.updateProblem(problem);
		problemDao.addEmployeeProblem(problem.getProblemId(),selectWork);
	}

	@Override
	public void addProblemSolve(ProblemInfo problem) {
		problemDao.updateProblem(problem);
	}

	@Override
	public void closeProblem(ProblemInfo problem) {
		problemDao.updateProblem(problem);
	}

	@Override
	public Result<List<ProblemInfo>> getAllProblem() {
		Result<List<ProblemInfo>> result = new Result<List<ProblemInfo>>();
		result.setResult(problemDao.getAllProblem());
		
		return result;
	}
	
}
